package com.taotao.web.service;




import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.service.ApiService;
import com.taotao.common.service.RedisService;
import com.taotao.manage.pojo.ItemDesc;
import com.taotao.web.bean.ItemVO;


@Service
public class ItemService {
	@Autowired
	private ApiService apiService;
	@Autowired
	private RedisService redisService;
	// 从配置文件中读取后台服务器的地址
    @Value("${MANAGE_TAOTAO_BASE_URL}")
    private String MANAGE_TAOTAO_BASE_URL;
    //从配置文件中读取key缓存
    @Value("${REDIS_ITEM_KEY}")
    protected String REDIS_ITEM_KEY;
    //从配置文件中读取redis缓存时间
    @Value("${REDIS_ITEM_TIME}")
    private Integer REDIS_ITEM_TIME;
    private static final ObjectMapper MAPPER = new ObjectMapper();
	public ItemVO queryById(Long itemId) {
		String key = "REDIS_ITEM_KEY" + itemId;
		//尝试从缓存中命中
		try {
			String cacheData = this.redisService.get(key);
			if (StringUtils.isNotEmpty(cacheData)) {
				//不为空,序列话json封装到bean中
				return MAPPER.readValue(cacheData, ItemVO.class);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		try {
			String url = MANAGE_TAOTAO_BASE_URL+"/rest/api/item/"+itemId;
			String jsonData = this.apiService.doGet(url);
			//查询到数据,返回之前放到redis缓存中
			this.redisService.set(key, jsonData, REDIS_ITEM_TIME);
			return MAPPER.readValue(jsonData, ItemVO.class);
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public ItemDesc queryByItemDescId(Long itemId) {
		// TODO Auto-generated method stub
				try {
					String url = MANAGE_TAOTAO_BASE_URL+"/rest/api/item/desc/"+itemId;
					String jsonData = this.apiService.doGet(url);
					return MAPPER.readValue(jsonData, ItemDesc.class);
				}catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		return null;
	}

}
